package com.lxs.doc.rocess.service.impl;


import com.lxs.doc.rocess.vo.FileDO;
import fr.opensagres.poi.xwpf.converter.xhtml.XHTMLConverter;
import fr.opensagres.poi.xwpf.converter.xhtml.XHTMLOptions;
import lombok.extern.slf4j.Slf4j;
import org.apache.poi.hssf.converter.ExcelToHtmlConverter;
import org.apache.poi.hssf.usermodel.HSSFWorkbook;
import org.apache.poi.hwpf.HWPFDocument;
import org.apache.poi.ss.usermodel.Workbook;
import org.apache.poi.xssf.usermodel.XSSFWorkbook;
import org.apache.poi.xwpf.usermodel.XWPFDocument;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.scheduling.annotation.Async;
import org.springframework.stereotype.Service;

import javax.xml.parsers.DocumentBuilderFactory;
import javax.xml.transform.OutputKeys;
import javax.xml.transform.Transformer;
import javax.xml.transform.TransformerFactory;
import javax.xml.transform.dom.DOMSource;
import javax.xml.transform.stream.StreamResult;
import java.io.ByteArrayOutputStream;
import java.io.InputStream;
import java.util.Arrays;

@Service
@Slf4j
public class FileConvertServiceImpl {

    // 异步转换文件
    @Async
    public void asyncConvertFile(Long fileId, InputStream inputStream, String fileType) {
        try {
            String targetPath = ""; // 转换后资源存储路径
            if (Arrays.asList("docx", "doc").contains(fileType)) {
                // 1. WORD转HTML
                targetPath = convertWordToHtml(fileId, inputStream, fileType);
            } else if (Arrays.asList("xlsx", "xls").contains(fileType)) {
                // 2. Excel转HTML
                targetPath = convertExcelToHtml(fileId, inputStream, fileType);
            } else if (Arrays.asList("xmind", "xmind8").contains(fileType)) {
                // 3. XMind转图片（多页生成ZIP包）
//                targetPath = convertXmindToImages(fileId, inputStream);
            }
        } catch (Exception e) {
            log.error("文件转换失败，fileId:{}", fileId, e);
            // 转换失败标记为“仅下载”
//            FileDO fileDO = fileMapper.selectById(fileId);
//            fileDO.setIsPreview(0);
//            fileMapper.updateById(fileDO);
        }
    }
    // WORD转HTML
    private String convertWordToHtml(Long fileId, InputStream inputStream, String fileType) throws Exception {
        String htmlContent = "";
        if ("docx".equals(fileType)) {
            XWPFDocument doc = new XWPFDocument(inputStream);
            XHTMLOptions options = XHTMLOptions.create().indent(4);
            ByteArrayOutputStream out = new ByteArrayOutputStream();
            XHTMLConverter.getInstance().convert(doc, out, options);
            htmlContent = out.toString("UTF-8");
        } else if ("doc".equals(fileType)) {
//            HWPFDocument doc = new HWPFDocument(inputStream);
//            HtmlDocumentConverter converter = new HtmlDocumentConverter(doc);
//            htmlContent = converter.getHtml();
        }
        // 存储HTML到MinIO
        String convertedPath = String.format("%s/%s_convert.html", fileId, fileId);
//        minioClient.putObject(
//                PutObjectArgs.builder()
//                        .bucket(manualBucket)
//                        .object(convertedPath)
//                        .stream(new ByteArrayInputStream(htmlContent.getBytes()), htmlContent.getBytes().length, -1)
//                        .contentType("text/html")
//                        .build()
//        );
        return convertedPath;
    }
    // Excel转HTML
    private String convertExcelToHtml(Long fileId, InputStream inputStream, String fileType) throws Exception {
        Workbook workbook = null;
        if ("xlsx".equals(fileType)) {
            workbook = new XSSFWorkbook(inputStream);
        } else if ("xls".equals(fileType)) {
            workbook = new HSSFWorkbook(inputStream);
        }
        // 转换Excel为HTML（保留表格样式）
        ExcelToHtmlConverter converter = new ExcelToHtmlConverter(DocumentBuilderFactory.newInstance().newDocumentBuilder().newDocument());
        converter.setOutputColumnHeaders(false);
        converter.setOutputHiddenColumns(true);
        converter.setOutputHiddenRows(true);
        converter.setOutputLeadingSpacesAsNonBreaking(false);
//        converter.processWorkbook(workbook);
        // 生成HTML内容
        Transformer transformer = TransformerFactory.newInstance().newTransformer();
        transformer.setOutputProperty(OutputKeys.ENCODING, "UTF-8");
        transformer.setOutputProperty(OutputKeys.INDENT, "yes");
        ByteArrayOutputStream out = new ByteArrayOutputStream();
        transformer.transform(new DOMSource(converter.getDocument()), new StreamResult(out));
        String htmlContent = out.toString("UTF-8");
        // 存储HTML到MinIO
        String convertedPath = String.format("%s/%s_convert.html", fileId, fileId);
//        minioClient.putObject(
//                PutObjectArgs.builder()
//                        .bucket(manualBucket)
//                        .object(convertedPath)
//                        .stream(new ByteArrayInputStream(htmlContent.getBytes()), htmlContent.getBytes().length, -1)
//                        .contentType("text/html")
//                        .build()
//        );
        return convertedPath;
    }
    // XMind转图片（多页生成ZIP包）
//    private String convertXmindToImages(Long fileId, InputStream inputStream) throws Exception {
//        // 加载XMind文件
//        IWorkbook workbook = Core.getWorkbookBuilder().loadFromStream(inputStream);
//        List<ISheet> sheets = workbook.getSheets();
//        // 临时目录存储单页图片
//        File tempDir = new File(System.getProperty("java.io.tmpdir") + "/xmind_" + fileId);
//        tempDir.mkdirs();
//        // 遍历sheet生成图片
//        for (int i = 0; i < sheets.size(); i++) {
//            ISheet sheet = sheets.get(i);
//            // 设置图片分辨率
//            ImageOutputStream imageOut = ImageIO.createImageOutputStream(
//                    new File(tempDir, "sheet_" + (i + 1) + ".png")
//            );
//            // 渲染sheet为图片
//            sheet.getPage().render(imageOut, ImageFormat.PNG, 2.0f); // 2倍分辨率
//            imageOut.close();
//        }
//        // 压缩图片为ZIP包
//        String zipPath = tempDir.getPath() + "/xmind_images.zip";
//        ZipUtil.zip(tempDir.getPath(), zipPath, true);
//        // 上传ZIP包到MinIO
//        String convertedPath = String.format("%s/%s_images.zip", fileId, fileId);
//        minioClient.putObject(
//                PutObjectArgs.builder()
//                        .bucket(manualBucket)
//                        .object(convertedPath)
//                        .stream(new FileInputStream(zipPath), new File(zipPath).length(), -1)
//                        .contentType("application/zip")
//                        .build()
//        );
//        // 清理临时文件
//        FileUtil.del(tempDir);
//        return convertedPath;
//    }
}
